package com.ideaaedi.springcloud.jd.commonspring.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import com.ideaaedi.springcloud.jd.commonds.entity.BaseCodeMsgEnum;
import com.ideaaedi.springcloud.jd.commonds.entity.Result;
import io.swagger.annotations.Api;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * spring-mvc 错误处理
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.B
 */
@ApiIgnore
@Controller
@Api(tags = "sys - 默认error处理")
@RequestMapping("${server.error.path:${error.path:/error}}")
public class DefaultErrorController extends BasicErrorController {
    
    public DefaultErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }
    
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Object resultStrObj = request.getAttribute(BaseConstant.OCCUR_JDX_EXCEPTION);
        if (resultStrObj != null) {
            return new ResponseEntity<>(JSON.parseObject(resultStrObj.toString()), getStatus(request));
        }
        Map<String, Object> originalMsgMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
        Result<Object> result = Result.failure(originalMsgMap, BaseCodeMsgEnum.SPRING_MVC_404_ERROR);
        return new ResponseEntity<>((JSONObject)JSON.toJSON(result), getStatus(request));
    }
}
